package com.netdimensions.confluence.plugins;

import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.confluence.user.AuthenticatedUserThreadLocal;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.util.Arrays;
import java.util.Map;

public final class CatalogMacro extends EkpMacro {
    public CatalogMacro() {
    }

    protected final String html(final Element root) {
        final StringBuilder result = new StringBuilder("<ul><li>Subcatalogs<ul>");

        for (final Node child : XPathUtils.nodes("child", root)) {
            result.append("<li><a href='");
            result.append(XPathUtils.string("link[@rel=\"alternate\"]/@href", child));
            result.append("' target='Course'>");
            result.append(XPathUtils.string("title", child));
            result.append("</a></li>");
        }

        result.append("</ul></li><li>Modules<ul>");

        for (final Node module : XPathUtils.nodes("module", root)) {
            result.append("<li><a href='");
            result.append(XPathUtils.string("link[@rel=\"alternate\"]/@href", module));
            result.append("' target='CATALOGWINDOW'>");
            result.append(XPathUtils.string("title", module));
            result.append("</a> (");
            result.append(XPathUtils.string("type", module));
            result.append(")<br />");
            result.append(XPathUtils.string("description", module));
            result.append("</li>");
        }

        result.append("</ul></li></ul>");
        return result.toString();
    }

    protected final String url(final Map params) {
        final Object id = params.get("id");
        return UrlUtils.url("catalog", id == null ? Arrays.asList(new Parameter("userId", AuthenticatedUserThreadLocal.getUser().getName())) : Arrays.asList(new Parameter("id", id.toString()), new Parameter("userId", AuthenticatedUserThreadLocal.getUser().getName())));
    }
}